import axios, {AxiosError, AxiosResponse, InternalAxiosRequestConfig} from "axios";
import {useUserStore} from "@/store";
import {resetRouter} from "@/router";
import {useSysStore} from "@/store/modules/sys";

// const baseURL = 'http://localhost:3000/api'
const service = axios.create({
    baseURL: import.meta.env.VITE_APP_BASE_API,
    // timeout: 50000,
    headers: {"Content-Type": "application/json;charset=utf-8"},
});

// 请求拦截器
service.interceptors.request.use(
    (config: InternalAxiosRequestConfig) => {
        const userStore = useUserStore()
        if (userStore.accessToken) {
            config.headers.Authorization = userStore.accessToken;
        }
        return config;
    },
    (error: any) => {
        return Promise.reject(error);
    }
);

// 响应拦截器
service.interceptors.response.use(
    (response: AxiosResponse<ResultType>) => {
        const {code, message, success} = response.data;
        if (success) {
            // 这里直接是返回了数据,因为请求里面都判断完了,至于里面的message已经没有用了
            return response.data.data
        }
        // 响应数据为二进制流处理(Excel导出)
        if (response.data instanceof ArrayBuffer) {
            return response;
        }

        // 只有错误的时候,message才有作用
        ElMessage.error(message || "系统出错");
        return Promise.reject(new Error(message || "Error"));
    },
    async (error: AxiosError) => {
        if (error.response?.data) {
            const {code, message} = error.response.data as ResultType;
            // accessToken 过期,重新登录
            // 被禁用的用户重新登陆
            if (code === 403) {
                handleExpire()
            } else {
                ElMessage.error(message || "系统出错");
            }
        }
        return Promise.reject(error.message);
    }
);

// 处理用户token过期
function handleExpire() {
    const sysStore = useSysStore()
    const userStore = useUserStore()
    if (sysStore.messageBoxNum === 0) {
        sysStore.messageBoxNum++
        ElMessageBox.alert("请重新登录", "提示:您的用户信息已过期", {
            confirmButtonText: "确定",
            type: "warning",
            showClose: false,
        }).then(() => {
            userStore.accessToken = ''
            sysStore.messageBoxNum = 0
            resetRouter()
        });
    }
}

export default service;
